package com.devicemantra.coordinate.dataobjects;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;

import com.devicemantra.coordinate.ds.tests.PMF;
import com.devicemantra.coordinate.exceptions.operations.CDepartmentDoesNotExistsException;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Key;

/** TODO - Most of the *Factory classes are written very badly 
 * put some thought into optimizing for performance */
public class SubDepartmentFactory 
{
	
		public static boolean checkSubDepartmentExists(CDepartment pDepartment,String pSubDepartmentName)
		{
			boolean lDoesExist = true;
			List<SubDepartment> lList = pDepartment.getSubDepartments();
			if( lList != null)
			System.out.println(pDepartment.getDepartmentName() + " Size of the list is " + lList.size());
			else
			System.out.println(pDepartment.getDepartmentName() + " *** List was null ****");	
			
			
			int lNumOfSubDepts = pDepartment.getNumOfSubDepartments();
			System.out.println("[CHECK] NUMBER OF SUB DEPTS IS " + lNumOfSubDepts);
			
			/* If there are no sub departments we do not need to check further */
			if(lNumOfSubDepts == 0 )
				return false;
							
			/* Now , we create a key using the department and sub department and then check whether 
			 * there exists an entity matching this key ? */			
			 
			Key lCombinedKey = createKey(pDepartment.getDepartmentName(),pSubDepartmentName);
			
			try
			{
				PersistenceManager pm = PMF.get().getPersistenceManager();
				pm.getObjectById(SubDepartment.class,lCombinedKey);
			} catch(JDOObjectNotFoundException e)
			{
				lDoesExist = false;
			}
			System.out.println("[CHECK] Sub department check returning " + lDoesExist);
			return lDoesExist;
		}
		
		public static boolean checkSubDepartmentExists(String pDepartmentName,String pSubDepartmentName)
		{
			CDepartment lDept = null;
			try {
				lDept = CDepartmentFactory.getDepartment(pDepartmentName);
			} catch (CDepartmentDoesNotExistsException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(lDept != null)
			{
				return checkSubDepartmentExists(lDept,pSubDepartmentName);
			}
			else
			{
				System.out.println("[COORDINATE] [ERROR] Department does not exist checking for Sub Dept ?");
				return false;
			}
		}
		
		
		
		public static Key createKey(String pDepartmentName, String pSubDepartmentName)
		{
			Key lNewSubDepartmentKey = new KeyFactory.Builder(CDepartment.class.getSimpleName(),pDepartmentName).
										addChild(SubDepartment.class.getSimpleName(),pSubDepartmentName).getKey();
			return lNewSubDepartmentKey;
		}
		
		public static List<SubDepartment> getAllSubDepartments(String pDepartmentName)
		{
			CDepartment lDept = null;
			List<SubDepartment> lSubDeptList = null;
			if( CDepartmentFactory.checkDepartmentExists(pDepartmentName))
			{
				try {
					lDept = CDepartmentFactory.getDepartment(pDepartmentName);
				} catch (CDepartmentDoesNotExistsException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if( lDept == null )
				{
					lSubDeptList =  null;
				}
				else
				{
					lSubDeptList =  lDept.getSubDepartments();
				}
			}
			return lSubDeptList;
		} 
	
		public static SubDepartment createNewSubDepartment(String pDepartmentName, String pNewSubDepartmentName)
		{
			/* First check whether such a Department exists using Keys */
			boolean lDoesDeptExist = CDepartmentFactory.checkDepartmentExists(pDepartmentName);
			if(false == lDoesDeptExist)
			{
				System.out.println("[COORDINATE][ERROR] Creating a sub department for a non existent Department ?");
				return null;
			}
			else
			{
				System.out.println("Checking  whether sub department exists");
				boolean lDoesSubDeptAlreadyExist = checkSubDepartmentExists(pDepartmentName,pNewSubDepartmentName);
				if(false == lDoesSubDeptAlreadyExist )
				{
					SubDepartment lSubDept = new SubDepartment(pNewSubDepartmentName);
					Key lSubDeptKey = createKey(pDepartmentName,pNewSubDepartmentName);
					lSubDept.setSubDepartmentId(lSubDeptKey);
					return lSubDept;
				}
				else
				{
					/* Sub department already exists */
					return null;
				}
			}
		}
		
		
		public static List<SubDepartment> getAllSubDepartments()
		{
			PersistenceManager pm = PMF.get().getPersistenceManager();
			javax.jdo.Query query = pm.newQuery(SubDepartment.class);
			//query.setFilter("mSubDepartmentName == lDeptName");
			//query.declareParameters("String lDeptName");
		    List<SubDepartment> lListSubDepts = (List<SubDepartment>) query.execute();
		    System.out.println("List size was " + lListSubDepts.size());
		    /*
		    Iterator<Department> lListDeptsIter = lListDepts.iterator();
		    while (lListDeptsIter.hasNext())
		    {
	               Department lDept = lListDeptsIter.next();
					System.out.println("DEPARTMENT NAME - " + lDept.getDepartmentName());
					List<SubDepartment> lSubDeptList = lDept.getSubDepartments();
					if( lSubDeptList == null )
					{
						System.out.println("List was null :(");
					}
					else
					{
						System.out.println("List was NOT null ");
					}
	        }
	        */
		    pm.detachCopyAll(lListSubDepts);
		    //List<Department> lNewListDepts = (List<Department>) pm.detachCopyAll(lListDepts);
		    pm.close();
		    return lListSubDepts;
		}
}
